import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores/user'

const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: '/',
            name: 'Home',
            component: () => import('../views/Home.vue'),
            meta: { 
                requiresAuth: true 
            }
        },
        {
            path: '/wishes',
            name: 'Wishes',
            component: () => import('../views/Wishes.vue'),
            meta: {
                requiresAuth: false // 愿望墙不需要登录
            }
        },
        {
            path: '/card',
            name: 'Card',
            component: () => import('../views/BirthdayCard.vue'),
            meta: {
                requiresAuth: true
            }
        },
        {
            path: '/Memories',
            name: 'Memories',
            component: () => import('../views/Memories.vue'),
            meta: {
                requiresAuth: true
            }
        },
        {
            path: '/login',
            name: 'Login',
            component: () => import('../views/Login.vue'),
            meta: {
                requiresAuth: false // 登录页面不需要登录
            }
        }
    ]
})

router.beforeEach((to, from, next) => {
    const userStore = useUserStore()
    
    // 如果要去登录页面，直接放行
    if (to.path === '/login') {
        next()
        return
    }

    // 检查路由是否需要认证
    if (to.meta.requiresAuth) {
        // 需要认证但未登录，重定向到登录页
        if (!userStore.isLoggedIn) {
            next({
                path: '/login',
                query: { redirect: to.fullPath } // 保存重定向地址
            })
        } else {
            // 已登录，允许访问
            next()
        }
    } else {
        // 不需要认证，直接放行
        next()
    }
})

export default router